﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Composite.Data;
using LCA.Utils;

public partial class C1Function : Composite.AspNet.UserControlFunction
{
    public override string FunctionDescription
    {
        get
        {
            return "System details";
        }
    }

    private string LCASystemId
    {
        get
        {
            string path = Composite.Core.Routing.Pages.C1PageRoute.GetPathInfo();
            //string path = HttpContext.Current.Request.Url.PathAndQuery;

            if (path == null)
                return null;
            else
                return path.Trim().Replace("/", "");

        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Composite.Core.Routing.Pages.C1PageRoute.RegisterPathInfoUsage();
        if (!IsPostBack)
        {
            RefreshComponents();
        }
    }

    private void RefreshComponents()
    {
        if (LCASystemId == null)
        {
            plhSystemInfo.Visible = true;
            litInfo.Text = "Please select node on the left to see system details";
            return;
        }

        int result;
        if (string.IsNullOrEmpty(LCASystemId) || !int.TryParse(LCASystemId, out result))
        {
            plhErrorMessage.Visible = true;
            litTopErrorMessage.Text = "System is not found.";
            return;
        }

        try
        {
            using (DataConnection conn = new DataConnection())
            {
                var system = (from s in conn.Get<LCA.Data.LCASystem>()
                              join u in conn.Get<LCA.Data.Unit>() on s.Unit equals u.Id into joined
                              from j in joined.DefaultIfEmpty()
                              where s.IsDeleted == false & s.LCASystemId == int.Parse(this.LCASystemId)
                              select new
                              {
                                  Id = s.Id,
                                  Name = s.Name,
                                  Description = s.Description,
                                  UnitName = j.Name,
                                  Amount = s.Amount,
                                  PicturePath = s.Picture,
                                  DiagramPath = s.Diagram,
                                  ChangeDate = s.ChangeDate,
                                  CreatedDate = s.CreatedDate
                              }).FirstOrDefault();

                if (system == null)
                {
                    plhErrorMessage.Visible = true;
                    litTopErrorMessage.Text = "System is not found.";
                    return;
                }

                // General Data

                plhSystemDetails.Visible = true;

                litSystemId.Text = system.Id.ToString();
                litTitle.Text = system.Name;
                litDescription.Text = system.Description;
                litUnit.Text = string.IsNullOrEmpty(system.UnitName) ? "-" : system.UnitName;
                litImg.Text = string.IsNullOrEmpty(system.PicturePath) ? "" : string.Format("<img src='{0}'/>", UrlHelper.GetMediaUrl(system.PicturePath));
                litAmount.Text = string.IsNullOrEmpty(system.Amount.Trim()) ? "-" : system.Amount.ToString();
                litCreationDate.Text = string.Format("{0:dd-MMM-yyyy}", system.CreatedDate);
                litModifiedDate.Text = string.Format("{0:dd-MMM-yyyy}", system.ChangeDate);

                var path = UrlHelper.GetMediaUrl(system.DiagramPath);
                if (path == null)
                {
                    lnkProductionDiagram.CssClass += " disabled";
                }
                else
                {
                    lnkProductionDiagram.NavigateUrl = path;
                }

                // Input
                var inputList = (from input in conn.Get<LCA.Data.LCASystemInput>()
                                join f in conn.Get<LCA.Data.Flow>() on input.RefItemId equals f.Id into fJoined
                                from ff in fJoined.DefaultIfEmpty()
                                join s in conn.Get<LCA.Data.LCASystem>() on input.RefItemId equals s.Id into sJoined
                                from ss in sJoined.DefaultIfEmpty()
                                join u in conn.Get<LCA.Data.Unit>() on input.Unit equals u.Id into joined
                                from j in joined.DefaultIfEmpty()
                                where input.RelatedSystem == system.Id
                                select new
                                {
                                    Id = input.Id,
                                    RefItemType = input.RefItemType,
                                    flowName = ff.Name,
                                    systemName = ss.Name,
                                    Amount = input.Amount,
                                    Unit = j.Name
                                }).AsEnumerable()
                                .Select((row, index) => new
                                {
                                    Count = index + 1,
                                    Id = row.Id,
                                    Item = string.Format("({0}) - {1}", row.RefItemType, row.flowName == null ? row.systemName : row.flowName ),
                                    Amount = row.Amount,
                                    Unit = row.Unit == null ? "-" : row.Unit
                                }).ToList();

                //inputList = inputList.OrderBy(x => x.Item);
                litInputChkTitle.Text = string.Format("Input ({0})", inputList.Count);

                gridInput.DataSource = inputList;
                gridInput.DataBind();
                if (inputList.Count > 0)
                    gridInput.HeaderRow.TableSection = TableRowSection.TableHeader;

                // Output
                var outputList = (from input in conn.Get<LCA.Data.LCASystemOutput>()
                                 join f in conn.Get<LCA.Data.Flow>() on input.RefItemId equals f.Id into fJoined
                                 from ff in fJoined.DefaultIfEmpty()
                                 join s in conn.Get<LCA.Data.LCASystem>() on input.RefItemId equals s.Id into sJoined
                                 from ss in sJoined.DefaultIfEmpty()
                                 join u in conn.Get<LCA.Data.Unit>() on input.Unit equals u.Id into joined
                                 from j in joined.DefaultIfEmpty()
                                 where input.RelatedSystem == system.Id
                                 select new
                                 {
                                     Id = input.Id,
                                     RefItemType = input.RefItemType,
                                     flowName = ff.Name,
                                     systemName = ss.Name,
                                     Amount = input.Amount,
                                     Unit = j.Name
                                 }).AsEnumerable()
                                .Select((row, index) => new
                                {
                                    Count = index + 1,
                                    Id = row.Id,
                                    Item = string.Format("({0}) - {1}", row.RefItemType, row.flowName == null ? row.systemName : row.flowName),
                                    Amount = row.Amount,
                                    Unit = row.Unit == null ? "-" : row.Unit
                                }).ToList();

                litOutputChkTitle.Text = string.Format("Output ({0})", outputList.Count);
                gridOutput.DataSource = outputList;
                gridOutput.DataBind();
                if (outputList.Count > 0)
                    gridOutput.HeaderRow.TableSection = TableRowSection.TableHeader;

                // Transportation A
                var taList = (from ta in conn.Get<LCA.Data.LCASystemTransportA>()
                              join f in conn.Get<LCA.Data.Flow>() on ta.Flow equals f.Id
                              join u in conn.Get<LCA.Data.Unit>() on ta.Unit equals u.Id into joined
                              from j in joined.DefaultIfEmpty()
                              where ta.RelatedSystem == system.Id
                              select new
                              {
                                  Id = ta.Id,
                                  flowName = f.Name,
                                  Amount = ta.Amount,
                                  Unit = j.Name
                              }).AsEnumerable()
                              .Select((row, index) => new
                              {
                                  Count = index + 1,
                                  Id = row.Id,
                                  Item = row.flowName,
                                  Amount = row.Amount,
                                  Unit = row.Unit == null ? "-" : row.Unit
                              }).ToList();

                litTransportAChkTitle.Text = string.Format("Transport A ({0})", taList.Count);
                gridTransportA.DataSource = taList;
                gridTransportA.DataBind();
                if(taList.Count > 0)
                    gridTransportA.HeaderRow.TableSection = TableRowSection.TableHeader;

                // Transportation B
                var tbList = (from tb in conn.Get<LCA.Data.LCASystemTransportB>()
                              join v in conn.Get<LCA.Data.HeavyVehicle>() on tb.Vehicle equals v.Id
                              join u in conn.Get<LCA.Data.Unit>() on tb.DistanceUnit equals u.Id into joined
                              from j in joined.DefaultIfEmpty()
                              join uu in conn.Get<LCA.Data.Unit>() on tb.kgLoadUnit equals uu.Id into joined1
                              from jj in joined1.DefaultIfEmpty()
                              where tb.RelatedSystem == system.Id
                              select new
                              {
                                  Id = tb.Id,
                                  Vehicle = v.Name,
                                  Distance = tb.Distance,
                                  UnitDistance = j.Name,
                                  KgLoad = tb.kgLoad,
                                  UnitKgLoad = jj.Name
                              }).AsEnumerable()
                              .Select((row, index) => new
                              {
                                  Count = index + 1,
                                  Id = row.Id,
                                  Vehicle = row.Vehicle,
                                  Distance = row.Distance,
                                  UnitDistance = row.UnitDistance == null ? "-" : row.UnitDistance,
                                  KgLoad = row.KgLoad,
                                  UnitKgLoad = row.UnitKgLoad == null ? "-" : row.UnitKgLoad
                              }).ToList();
   
                litTransportBChkTitle.Text = string.Format("Transport B ({0})", tbList.Count);
                gridTransportB.DataSource = tbList;
                gridTransportB.DataBind();
                if (tbList.Count > 0)
                    gridTransportB.HeaderRow.TableSection = TableRowSection.TableHeader;

                // Focus at selected tree node.
                string script = @" $(document).ready(function () { clickSystem('" + system.Id + "'); });";
                Page.ClientScript.RegisterStartupScript(GetType(), ClientID + "_TriggerClickFlow", script, true);
            }
        }
        catch (Exception ex)
        {
            plhErrorMessage.Visible = true;
            litTopErrorMessage.Text = string.Format("Problem occured.</br>Details: {0} <br/>", ex.Message);
            plhSystemDetails.Visible = false;
            return;
        }
    }
}